<!--
 * @Description: 动态搜索组件 - 支持输入框、下拉框、时间框
 * @Author: Auto
 * @Date: 2025-01-27
-->
<template>
  <div class="dynamic-search">
    <div class="search-form">
      <div 
        v-for="(field, index) in searchFields" 
        :key="index"
        class="search-item"
      >
        <span class="search-label">{{ field.label }}:</span>
        
        <!-- 输入框 -->
        <a-input
          v-if="field.type === 'input'"
          v-model:value="searchValues[field.key]"
          :placeholder="field.placeholder || `请输入${field.label}`"
          size="small"
          allow-clear
          @pressEnter="handleSearch"
          @change="handleFieldChange(field.key)"
        />
        
        <!-- 下拉框 -->
        <a-select
          v-else-if="field.type === 'select'"
          v-model:value="searchValues[field.key]"
          :placeholder="field.placeholder || `请选择${field.label}`"
          size="small"
          allow-clear
          :options="field.options || []"
          @change="handleFieldChange(field.key)"
          style="width: 100%"
        />
        
        <!-- 时间选择器 -->
        <a-date-picker
          v-else-if="field.type === 'date'"
          v-model:value="searchValues[field.key]"
          :placeholder="field.placeholder || `请选择${field.label}`"
          size="small"
          allow-clear
          :format="field.format || 'YYYY-MM-DD'"
          @change="handleFieldChange(field.key)"
          style="width: 100%"
        />
        
        <!-- 时间范围选择器 -->
        <a-range-picker
          v-else-if="field.type === 'daterange'"
          v-model:value="searchValues[field.key]"
          :placeholder="field.placeholder || ['开始时间', '结束时间']"
          size="small"
          allow-clear
          :format="field.format || 'YYYY-MM-DD'"
          @change="handleFieldChange(field.key)"
          style="width: 100%"
        />
      </div>
      
      <div class="search-actions">
        <a-button type="primary" size="small" @click="handleSearch">搜索</a-button>
        <a-button size="small" @click="handleReset">重置</a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue'
import dayjs, { Dayjs } from 'dayjs'

export interface SearchField {
  key: string // 字段key
  label: string // 字段标签
  type: 'input' | 'select' | 'date' | 'daterange' // 字段类型
  placeholder?: string // 占位符
  format?: string // 时间格式（仅时间类型有效）
  options?: Array<{ label: string; value: any }> // 下拉框选项（仅select类型有效）
}

interface Props {
  searchFields: SearchField[] // 搜索字段配置
  modelValue?: Record<string, any> // 搜索值（v-model）
}

const props = withDefaults(defineProps<Props>(), {
  searchFields: () => [],
  modelValue: () => ({})
})

const emit = defineEmits<{
  'update:modelValue': [value: Record<string, any>]
  'search': [values: Record<string, any>]
  'reset': []
}>()

// 搜索值
const searchValues = reactive<Record<string, any>>({})

// 初始化搜索值
const initSearchValues = () => {
  props.searchFields.forEach(field => {
    if (props.modelValue && props.modelValue[field.key] !== undefined) {
      searchValues[field.key] = props.modelValue[field.key]
    } else {
      searchValues[field.key] = field.type === 'daterange' ? null : (field.type === 'select' ? undefined : '')
    }
  })
}

// 初始化
initSearchValues()

// 监听props变化
watch(() => props.searchFields, () => {
  initSearchValues()
}, { deep: true })

watch(() => props.modelValue, () => {
  initSearchValues()
}, { deep: true })

// 字段值变化
const handleFieldChange = (key: string) => {
  emit('update:modelValue', { ...searchValues })
}

// 搜索
const handleSearch = () => {
  const values: Record<string, any> = {}
  
  Object.keys(searchValues).forEach(key => {
    const value = searchValues[key]
    if (value !== null && value !== undefined && value !== '') {
      // 处理时间范围
      if (Array.isArray(value) && value.length === 2) {
        values[`${key}Start`] = value[0] ? dayjs(value[0]).format('YYYY-MM-DD') : ''
        values[`${key}End`] = value[1] ? dayjs(value[1]).format('YYYY-MM-DD') : ''
      } else if (value && typeof value === 'object' && '$d' in value) {
        // 处理单个时间（dayjs对象有$d属性）
        values[key] = dayjs(value).format('YYYY-MM-DD')
      } else {
        values[key] = value
      }
    }
  })
  
  emit('update:modelValue', { ...searchValues })
  emit('search', values)
}

// 重置
const handleReset = () => {
  props.searchFields.forEach(field => {
    searchValues[field.key] = field.type === 'daterange' ? null : (field.type === 'select' ? undefined : '')
  })
  emit('update:modelValue', { ...searchValues })
  emit('reset')
  emit('search', {})
}
</script>

<style scoped lang="less">
.dynamic-search {
  padding: 8px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 8px;
  
  .search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    
    .search-item {
      display: flex;
      align-items: center;
      gap: 4px;
      min-width: 150px;
      
      .search-label {
        font-size: 12px;
        color: #666;
        white-space: nowrap;
        flex-shrink: 0;
      }
      
      // 输入框和选择器样式
      :deep(.ant-input),
      :deep(.ant-select-selector),
      :deep(.ant-picker) {
        font-size: 12px;
      }
    }
    
    .search-actions {
      display: flex;
      gap: 8px;
      margin-left: auto;
      flex-shrink: 0;
    }
  }
}
</style>

